<template>
  <div class="job-category-page">
    <!-- 一级分类导航 -->
    <div class="category-nav">
      <el-button
        v-for="(category, index) in firstLevelCategories"
        :key="index"
        @click="handleCateOneClick(category)"
        :class="['category-btn', activeCategoryId === category.id ? 'active' : '']"
        type="primary"
        plain
      >
        {{ category.name }}
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="3" animated></el-skeleton>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error">
      <el-alert type="error" :title="error"></el-alert>
    </div>

    <!-- 空状态提示 -->
    <div v-if="!loading && !error && (!jobpostings || jobpostings.length === 0)" class="empty-state">
      <el-empty description="暂无相关职位信息"></el-empty>
    </div>

    <!-- 职位列表 -->
    <div class="job-list" v-if="jobpostings && jobpostings.length > 0">
      <div
        v-for="(job, index) in jobpostings"
        :key="index"
        class="job-card"
        @mouseenter="handleMouseEnter(index)"
        @mouseleave="handleMouseLeave(index)"
        @click="goToDetail(job.id)"
      >
        <div class="job-info">
          <div class="job-header">
            <h3 class="job-title">{{ job.title }}</h3>
            <span class="salary">{{ job.money }}</span>
          </div>
          <div class="job-meta">
             <span><el-icon><location /></el-icon>
           {{ job.city.name }}</span>
            <span>{{ job.label }}</span>
           <span> <el-icon><school /></el-icon>
            {{ job.education }}</span>
            <el-icon v-if="job.tags && job.tags.length > 0"><collection-tag /></el-icon>
            <span v-if="job.labels && job.labels.length > 0">{{ job.labels.join(' ') }}</span>
          </div>
          <div class="company-info">
            <img :src="job.company.logo || 'https://picsum.photos/100/100'" alt="Company Logo" class="company-logo" />
            <div class="company-details">
              <div class="company-name">{{ job.company.name }}</div>
              <div class="job-meta">{{ job.company.description }}</div>
            </div>
          </div>
        </div>
        <div class="job-actions" :class="{'show-actions': isHoveringIndex === index}">
          <el-button size="small" type="primary" plain>详情</el-button>
          <el-button size="small" type="warning" plain>收藏</el-button>
        </div>
      </div>
    </div>

    <!-- 查看更多按钮 -->
    <div class="load-more-container" v-if="jobpostings && jobpostings.length > 0">
      <el-button @click="loadMore" type="primary" plain>查看更多</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import {
  Location,
  School,
  CollectionTag
} from '@element-plus/icons-vue';
import { ElEmpty, ElSkeleton, ElTag, ElButton, ElIcon, ElAlert } from 'element-plus';

// 路由跳转





const firstLevelCategories = ref([]);
const loading = ref(false);
const error = ref('');
const activeCategoryId = ref(null);
const jobpostings = ref([]);
const isHoveringIndex = ref(-1);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

onMounted(async () => {
  loading.value = true;
  try {
    const response = await axios.get('http://127.0.0.1:8000/home/JobCateOne/');
    if (response.data.code === 200) {
      firstLevelCategories.value = response.data.data;
      if (firstLevelCategories.value.length > 0) {
        activeCategoryId.value = firstLevelCategories.value[0].id;
        handleCateListClick(activeCategoryId.value);
      }
    } else {
      error.value = response.data.msg || '获取分类数据失败';
    }
  } catch (err) {
    error.value = '网络异常，请重试';
    console.error('请求分类树失败：', err);
  } finally {
    loading.value = false;
  }
});

const handleCateOneClick = (category) => {
  activeCategoryId.value = category.id;
  handleCateListClick(category.id);
  const jobList = document.querySelector('.job-list');
  if (jobList) jobList.scrollIntoView({ behavior: 'smooth' });
};

const handleCateListClick = async (categoryId) => {
  loading.value = true;
  error.value = '';
  page.value = 1;
  try {
    const response = await axios.get('http://127.0.0.1:8000/home/jobcateList/', {
      params: {
        jobcate_id: categoryId,
        page: page.value,
        page_size: pageSize.value
      }
    });
    if (response.data.code === 200) {
       let data = response.data.data.results || response.data.data;
      data = data.slice(0, 9);
      jobpostings.value = data;
      total.value = data.length;
    } else {
      error.value = response.data.error || '获取招聘信息失败';
      jobpostings.value = [];
    }
  } catch (err) {
    error.value = '网络异常，请重试';
    jobpostings.value = [];
    console.error('请求招聘信息失败：', err);
  } finally {
    loading.value = false;
  }
};

const handleMouseEnter = (index) => {
  isHoveringIndex.value = index;
};

const handleMouseLeave = () => {
  isHoveringIndex.value = -1;
};

const loadMore = async () => {
  if (jobpostings.value.length >= total.value) return;
  page.value++;
  loading.value = true;
  try {
    const response = await axios.get('http://127.0.0.1:8000/home/jobcateList/', {
      params: {
        jobcate_id: activeCategoryId.value,
        page: page.value,
        page_size: pageSize.value
      }
    });
    if (response.data.code === 200) {
      const newJobs = response.data.data.results || response.data.data;
      jobpostings.value = [...jobpostings.value, ...newJobs];
    }
  } catch (err) {
    console.error('加载更多失败：', err);
  } finally {
    loading.value = false;
  }
};

watch(activeCategoryId, (newId) => {
  if (newId) {
    handleCateListClick(newId);
  }
});
</script>

<style scoped>
.job-category-page {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
}

.category-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  justify-content: center;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
}

.category-btn {
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 80px;
  text-align: center;
  border: 1px solid #d9d9d9;
  background-color: #f8f9fa;
  color: #495057;
}

.category-btn.active,
.category-btn:hover {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.loading {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.error {
  margin: 20px 0;
}

.job-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.job-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
}

.job-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.job-info {
  padding: 16px;
}

.job-header {
  display: flex;
  justify-content: space-between; /* 关键：让子元素两端对齐 */
  align-items: center;
  margin-bottom: 8px;
}

.job-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.salary {
  font-size: 14px;
  color: #ff4d4f;
}

.job-meta {
  color: #666;
  font-size: 14px;
  margin: 8px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.job-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.company-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border-top: 1px solid #f5f5f5;
}

.company-logo {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  object-fit: cover;
}

.company-details {
  flex: 1;
}

.company-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.company-meta {
  font-size: 12px;
  color: #999;
}

.job-actions {
  position: absolute;
  right: 16px;
  bottom: 16px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.job-card:hover .job-actions {
  opacity: 1;
}

.show-actions {
  opacity: 1;
}

.load-more-container {
  margin-top: 30px;
  text-align: center;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}
</style>